use diesel::prelude::*;
use diesel::MysqlConnection;

use super::model::*;
use crate::database::{crud, schema::image, DbError};
use crate::{db_creates, db_deletes, db_read_count_from_offset_by_field};

db_creates!(image, Image, NewImage, creates);
db_read_count_from_offset_by_field!(image, Image, read_count_from_offset_by_pid, pid, i32);
db_deletes!(image, deletes);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        database::{
            self, establish_connection,
            table::{category::model::NewCategory, post::model::NewPost, tag::model::NewTag},
        },
        test_db_create, test_db_reads_by_field,
    };

    fn insert_test_data(conn: &mut MysqlConnection) -> (i32, i32, i32) {
        let cid = database::table::category::crud::create(
            conn,
            NewCategory {
                name: "CATE",
                desc: "DESC",
                cover: "COVER",
                slug: "LINK",
            },
        )
        .unwrap();
        let aid = database::table::tag::crud::create(
            conn,
            NewTag {
                name: "AUTHOR",
                desc: "DESC",
                avatar: "AVATAR",
                slug: "LINK",
                cid,
            },
        )
        .unwrap();
        let tid = database::table::tag::crud::create(
            conn,
            NewTag {
                name: "TAG1",
                desc: "DESC1",
                avatar: "AVATAR1",
                slug: "LINK1",
                cid,
            },
        )
        .unwrap();
        let pid1 = database::table::post::crud::create(
            conn,
            NewPost {
                title: "TITLE1",
                cover: "COVER1",
                tid: aid,
                sid: "SID1",
                tids: "".to_string(),
            },
        )
        .unwrap();
        let pid2 = database::table::post::crud::create(
            conn,
            NewPost {
                title: "TITLE2",
                cover: "COVER2",
                tid: aid,
                sid: "SID2",
                tids: "".to_string(),
            },
        )
        .unwrap();
        creates(
            conn,
            vec![
                NewImage {
                    pid: pid1,
                    url: "IMAGE1".to_string(),
                },
                NewImage {
                    pid: pid1,
                    url: "IMAGE2".to_string(),
                },
                NewImage {
                    pid: pid2,
                    url: "IMAGE3".to_string(),
                },
            ],
        )
        .unwrap();
        (1, tid, pid1)
    }

    test_db_create!();
    test_db_reads_by_field!(test_read_by_pid, read_count_from_offset_by_pid, 2);
}
